package JUC.printWhen5;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * @className: LockSupportList
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/5 20:53
 */
public class LockSupportList {
    private List<Integer> list = new ArrayList<>();
    public void add(Integer i){
        list.add(i);
    }
    public int size(){
        return list.size();
    }

    public static void main(String[] args) throws InterruptedException {
        LockSupportList list = new LockSupportList();
        Thread1 t1 = new Thread1(null , list);
        Thread2 t2 = new Thread2(null , list); ;
        t1.setT(t2);
        t2.setT(t1);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

    }
    public static class Thread2 extends Abs{
        public Thread2(Thread t , LockSupportList list){
            super(t , list);
        }

        @Override
        public void run() {
            LockSupport.park();
            System.out.println("list size is " + list.size());
            LockSupport.unpark(t);
        }
    }
    public static class Thread1 extends Abs {
        public Thread1(Thread t , LockSupportList list){
            super(t , list);
        }

        @Override
        public void run() {
            for(int i = 0 ; i < 10 ; i++){
                list.add(i);
                System.out.println("add " + i);
                if(list.size() == 4){
                    LockSupport.unpark(t);
                    LockSupport.park();
                }
            }
        }
    }


    public static class Abs extends Thread{
        protected Thread t ;
        protected LockSupportList list ;

        public void setT(Thread t) {
            this.t = t;
        }

        public Abs(Thread t , LockSupportList list){
            this.t = t ;
            this.list = list ;
        }

        @Override
        public void run() {

        }
    }
}
